<?php


namespace app\common\model;


use addons\epay\library\Service;
use Exception;
use think\Db;
use think\Model;

class UserRechargeLogModel extends Model
{
    protected $name = 'user_recharge_log';



    /**
     * 充值
     *
     * @param int $user_id
     * @param string $openid
     * @param string $money 充值金额
     * @param string $platform 平台:pc=PC,mini=微信小程序,app=App
     * @param string $pay_type 支付类型:alipay=支付宝,wxpay=微信
     */
    public function rechargeMoney($params, $user_id)
    {
        extract($params);

        Db::startTrans();
        try {
            $outTradeNo = OrderNo();
            $insert = [
                'user_id'    => $user_id,
                'money'      => $money,
                'is_pay'     => 0,
                'createtime' => time(),
                'trade_no'   => $outTradeNo,
            ];

            $id = $this->insertGetId($insert);

            $totalFee = $money;
            $body = '钱包充值';

            switch ($pay_type){
                // 微信支付
                case 'wxpay':
                    $paytype = 'wechat';
                    switch ($platform){
                        // 小程序支付
                        case 'mini':
                            $method = 'mini';
                            break;
                        case 'pc':
                            $method = 'scan';
                            break;
                        case 'app':
                            break;
                    }
                    $notifyUrl = GetDomain() . '/api/wallet/notify/paytype/'.$paytype.'/method/'.$method;
                    $params = [
                        'type'         => $paytype,
                        'orderid'      => $outTradeNo,
                        'title'        => $body,
                        'amount'       => $totalFee,
                        'method'       => $method,
                        'openid'       => $openid,
                        'notifyurl'    => $notifyUrl,
                    ];
                    $payInfo = Service::submitOrder($params);
                    if($platform == 'pc'){
                        if (!isset($payInfo['code_url'])) {
                            Exception('创建订单失败，请返回重试',44104);
                        }
                    }
                    $data = [
                        'trade_no' => $outTradeNo,
                        'payInfo' => $payInfo,
                        'paytype' => $paytype,
                        'amount' => $totalFee,
                    ];
                    Db::commit();
                    return [
                        'code' => 200,
                        'msg'  => '请求成功',
                        'data' => $data
                    ];
                    break;
                // 支付宝支付
                case 'alipay':
                    switch ($platform) {
                        case 'app':
                            $paytype = 'alipay';
                            $method = 'app';
                            $notifyUrl = GetDomain() . '/api/wallet/notify/paytype/'.$paytype.'/method/'.$method;
                            $params = [
                                'type'         => $paytype,
//                                'out_trade_no' => $outTradeNo,
                                'orderid'      => $outTradeNo,
                                'title'        => $body,
                                'amount'       => $totalFee,
                                'method'       => $method,
                                'openid'       => $openid,
                                'notifyurl'    => $notifyUrl,
                            ];
                            $payInfo = Service::submitOrder($params);

                            $data = [
                                'trade_no' => $outTradeNo,
                                'payInfo' => $payInfo
                            ];
                            Db::commit();
                            return [
                                'code' => 200,
                                'msg'  => '请求成功',
                                'data' => $data
                            ];
                            break;
                    }
                    break;
            }
            Exception('暂不支持该支付方式',44104);
        }catch (\Exception $e) {
            Db::rollback();
            return [
                'code' => $e->getCode(),
                'msg' => $e->getMessage(),
                'data' => $e->getLine()
            ];
        }
    }


    /**
     * 微信小程序支付下单回调处理
     */
    public function notify($type,$method)
    {
        Db::startTrans();
        try {
            $this->xmlLog('充值回调开始');
            $pay = \addons\epay\library\Service::checkNotify($type);
            if (!$pay) {
                echo '签名错误';
                throw new Exception('签名错误');
            }
            $data = $pay->verify();
            $this->xmlLog('充值回调开始处理:'.JsonEn($data));

            //回调处理
            $rechargeInfo = $this->get(['trade_no' => $data['out_trade_no']]);
            if(!$rechargeInfo) {
                throw new Exception('未找到充值单',47101);
            }
            if($rechargeInfo->is_pay != 0) {
                throw new Exception('充值单状态错误',47102);
            }

            $pay_price = 0;
            $pay_time = 0;
            $out_trade_no = 0;
            switch ($type){
                case 'wechat':
                    $pay_price = $data['total_fee'] / 100;
                    $pay_time = strtotime($data['time_end']);
                    $out_trade_no = $data['transaction_id'];
                    break;
                case 'alipay':
                    $pay_price = $data['total_amount'];
                    $pay_time = strtotime($data['gmt_payment']);
                    $out_trade_no = $data['trade_no'];
                    break;
            }

            //修改订单状态
            $update['is_pay'] = 1;
            $update['pay_time'] = $pay_time;
//            $update['pay_price'] = $pay_price;
            $update['out_trade_no'] = $out_trade_no;

            $update_res = $this->where(['id' => $rechargeInfo->id])->update($update);
            if(!$update_res){
                $this->xmlLog('更新订单失败,订单号:'.$data['out_trade_no']);
            }

            // 生成账单
            // 增加余额,新增账单记录
            $type_array = ['wechat' => '微信','alipay' => '支付宝'];
            $method_array = ['mini' => '小程序','app' => 'APP','pc','PC'];
            $memo = $type_array[$type] . $method_array[$method];
            \app\common\model\User::money( $pay_price, $rechargeInfo->user_id, "充值渠道: ".$memo);

            Db::commit();

            //你可以在这里你的业务处理逻辑,比如处理你的订单状态、给会员加余额等等功能
            //下面这句必须要执行,且在此之前不能有任何输出
            return $pay->success()->send();
        }catch (Exception $e) {
            Db::rollback();
//            $returnString = '回调失败,订单号:'.$data['out_trade_no'].',错误码:'.$e->getCode().',错误描述:'.$e->getMessage();
            $returnString = '回调失败:错误码:'.$e->getCode().',错误描述:'.$e->getMessage();
            $this->xmlLog($returnString);
        }
    }

    protected function xmlLog($str)
    {
        $file_dir = '.././runtime/log/recharge/';
        create($file_dir);
        $file_name = $file_dir.date('Ymd').'.txt';
        fopen($file_name, 'a+');
        $str = PHP_EOL.'[PayLog]'.PHP_EOL.'['.date('Y-m-d H:i:s').']'.PHP_EOL.'[json_data]'.PHP_EOL.$str;
        file_put_contents($file_name,$str,FILE_APPEND);

        \think\Log::write($str);
    }
}